// 模拟数据服务，用于前端原型演示
import type { Dataset, Entity, FeatureView, FeatureTask, Job, Model, ApiResponse } from '../types';
import { generateId, parseCSV } from '../utils/fileUtils';

// 本地存储键名
const STORAGE_KEYS = {
  DATASETS: 'ai_platform_datasets',
  ENTITIES: 'ai_platform_entities',
  FEATURE_VIEWS: 'ai_platform_feature_views',
  FEATURE_TASKS: 'ai_platform_feature_tasks',
  JOBS: 'ai_platform_jobs',
  MODELS: 'ai_platform_models'
};

// 获取本地存储数据
const getFromStorage = <T>(key: string): T[] => {
  const data = localStorage.getItem(key);
  return data ? JSON.parse(data) : [];
};

// 保存到本地存储
const saveToStorage = <T>(key: string, data: T[]): void => {
  localStorage.setItem(key, JSON.stringify(data));
};

// 模拟数据集
const mockDatasets: Dataset[] = [
  {
    id: '1',
    name: '客户流失预测数据',
    description: '电信客户流失预测数据集',
    uploadedAt: new Date().toISOString(),
    fileSize: 102400,
    rows: 1000,
    columns: [
      { name: 'customer_id', type: 'string', isSelected: true, isTarget: false },
      { name: 'gender', type: 'string', isSelected: true, isTarget: false },
      { name: 'senior_citizen', type: 'boolean', isSelected: true, isTarget: false },
      { name: 'tenure', type: 'number', isSelected: true, isTarget: false },
      { name: 'monthly_charges', type: 'number', isSelected: true, isTarget: false },
      { name: 'total_charges', type: 'number', isSelected: true, isTarget: false },
      { name: 'churn', type: 'boolean', isSelected: true, isTarget: true }
    ]
  },
  {
    id: '2',
    name: '电商用户行为特征集',
    description: '电商平台用户行为数据经过特征工程处理后的特征集',
    uploadedAt: new Date(Date.now() - 86400000).toISOString(), // 1天前
    fileSize: 204800,
    rows: 5000,
    columns: [
      { name: 'user_id', type: 'string', isSelected: true, isTarget: false },
      { name: 'age', type: 'number', isSelected: true, isTarget: false },
      { name: 'gender', type: 'string', isSelected: true, isTarget: false },
      { name: 'category_preference', type: 'string', isSelected: true, isTarget: false },
      { name: 'avg_order_value', type: 'number', isSelected: true, isTarget: false },
      { name: 'purchase_frequency', type: 'number', isSelected: true, isTarget: false },
      { name: 'last_purchase_days', type: 'number', isSelected: true, isTarget: false },
      { name: 'is_vip', type: 'boolean', isSelected: true, isTarget: false },
      { name: 'conversion_rate', type: 'number', isSelected: true, isTarget: true }
    ],
    type: 'feature'
  },
  {
    id: '3',
    name: '金融风控特征集',
    description: '金融贷款申请数据经过特征工程处理后的特征集',
    uploadedAt: new Date(Date.now() - 172800000).toISOString(), // 2天前
    fileSize: 153600,
    rows: 8000,
    columns: [
      { name: 'applicant_id', type: 'string', isSelected: true, isTarget: false },
      { name: 'age', type: 'number', isSelected: true, isTarget: false },
      { name: 'income', type: 'number', isSelected: true, isTarget: false },
      { name: 'employment_length', type: 'number', isSelected: true, isTarget: false },
      { name: 'loan_amount', type: 'number', isSelected: true, isTarget: false },
      { name: 'credit_score', type: 'number', isSelected: true, isTarget: false },
      { name: 'debt_to_income', type: 'number', isSelected: true, isTarget: false },
      { name: 'previous_defaults', type: 'number', isSelected: true, isTarget: false },
      { name: 'loan_purpose', type: 'string', isSelected: true, isTarget: false },
      { name: 'approved', type: 'boolean', isSelected: true, isTarget: true }
    ],
    type: 'feature'
  }
];

// 模拟实体
const mockEntities: Entity[] = [
  {
    id: '1',
    name: '客户',
    description: '电信客户实体',
    dimensions: ['customer_id'],
    features: ['gender', 'senior_citizen', 'tenure', 'monthly_charges', 'total_charges'],
    datasetId: '1'
  }
];

// 模拟特征视图
const mockFeatureViews: FeatureView[] = [
  {
    id: '1',
    name: '客户流失预测特征视图',
    description: '用于预测客户流失的特征集合',
    entities: ['1'],
    features: ['gender', 'senior_citizen', 'tenure', 'monthly_charges', 'total_charges'],
    createdAt: new Date().toISOString()
  }
];

// 模拟作业
const mockJobs: Job[] = [
  {
    id: '1',
    name: '随机森林模型训练',
    type: 'training',
    status: 'completed',
    featureViewId: '1',
    modelConfig: {
      modelType: 'RandomForest',
      hyperparameters: {
        n_estimators: 100,
        max_depth: 10
      }
    },
    createdAt: new Date(Date.now() - 3600000).toISOString(),
    updatedAt: new Date().toISOString(),
    metrics: {
      accuracy: 0.85,
      precision: 0.78,
      recall: 0.82,
      f1Score: 0.80
    }
  },
  {
    id: '2',
    name: '梯度提升树模型训练',
    type: 'training',
    status: 'completed',
    featureViewId: '1',
    modelConfig: {
      modelType: 'XGBoost',
      hyperparameters: {
        learning_rate: 0.1,
        max_depth: 6,
        n_estimators: 100
      }
    },
    createdAt: new Date(Date.now() - 7200000).toISOString(),
    updatedAt: new Date().toISOString(),
    metrics: {
      accuracy: 0.87,
      precision: 0.81,
      recall: 0.84,
      f1Score: 0.82
    }
  },
  // 添加一个评估任务示例
  {
    id: '3',
    name: '客户流失预测模型评估',
    type: 'evaluation',
    status: 'completed',
    featureViewId: '1',
    modelConfig: {
      modelType: 'XGBoost',
      modelName: '客户流失预测模型',
      modelVersion: 1,
      hyperparameters: {
        learning_rate: 0.1,
        max_depth: 8,
        n_estimators: 200
      }
    },
    createdAt: new Date(Date.now() - 1800000).toISOString(), // 30分钟前
    updatedAt: new Date().toISOString(),
    metrics: {
      accuracy: 0.88,
      precision: 0.82,
      recall: 0.85,
      f1Score: 0.83
    }
  }
];

// 模拟特征工程任务
const mockFeatureTasks: FeatureTask[] = [
  {
    id: '1',
    name: '电商用户行为特征工程',
    type: 'visual',
    status: 'completed',
    datasetId: '2',
    progress: 100,
    flowData: {
      nodes: [
        {
          id: '1',
          type: 'data_source',
          position: { x: 100, y: 100 },
          data: { label: '数据源', datasetId: '2' }
        },
        {
          id: '2',
          type: 'feature_transform',
          position: { x: 300, y: 100 },
          data: { label: '特征变换', transformType: 'normalize' }
        },
        {
          id: '3',
          type: 'feature_selection',
          position: { x: 500, y: 100 },
          data: { label: '特征选择', method: 'correlation' }
        }
      ],
      connections: [
        { id: 'e1-2', source: '1', target: '2' },
        { id: 'e2-3', source: '2', target: '3' }
      ]
    },
    createdAt: new Date(Date.now() - 86400000).toISOString(), // 1天前
    completedAt: new Date(Date.now() - 82800000).toISOString(), // 23小时前
    logs: [
      '[10:00:00] 开始执行特征工程任务...',
      '[10:00:05] 加载数据集: 电商用户行为特征集',
      '[10:00:10] 执行数据预处理...',
      '[10:00:25] 执行特征变换: normalize',
      '[10:00:40] 执行特征选择: correlation',
      '[10:00:50] 任务执行完成！'
    ]
  },
  {
    id: '2',
    name: '金融风控特征工程',
    type: 'visual',
    status: 'completed',
    datasetId: '3',
    progress: 100,
    flowData: {
      nodes: [
        {
          id: '1',
          type: 'data_source',
          position: { x: 100, y: 100 },
          data: { label: '数据源', datasetId: '3' }
        },
        {
          id: '2',
          type: 'feature_transform',
          position: { x: 300, y: 100 },
          data: { label: '特征变换', transformType: 'standardize' }
        },
        {
          id: '3',
          type: 'feature_creation',
          position: { x: 500, y: 100 },
          data: { label: '特征创建', method: 'polynomial' }
        }
      ],
      connections: [
        { id: 'e1-2', source: '1', target: '2' },
        { id: 'e2-3', source: '2', target: '3' }
      ]
    },
    createdAt: new Date(Date.now() - 172800000).toISOString(), // 2天前
    completedAt: new Date(Date.now() - 169200000).toISOString(), // 47小时前
    logs: [
      '[09:00:00] 开始执行特征工程任务...',
      '[09:00:05] 加载数据集: 金融风控特征集',
      '[09:00:15] 执行数据预处理...',
      '[09:00:30] 执行特征变换: standardize',
      '[09:00:45] 执行特征创建: polynomial',
      '[09:01:00] 任务执行完成！'
    ]
  }
]

// 模拟模型
const mockModels: Model[] = [
  {
    id: '1',
    name: '客户流失预测模型 V1',
    description: '基于XGBoost的客户流失预测模型',
    jobId: '2',
    createdAt: new Date().toISOString(),
    metrics: {
      accuracy: 0.88,
      precision: 0.82,
      recall: 0.85,
      f1Score: 0.83
    },
    config: {
      modelType: 'XGBoost',
      hyperparameters: {
        learning_rate: 0.1,
        max_depth: 8,
        n_estimators: 200
      }
    },
    version: 1
  }
];

// 初始化本地存储
const initializeStorage = () => {
  if (!localStorage.getItem(STORAGE_KEYS.DATASETS)) {
    saveToStorage(STORAGE_KEYS.DATASETS, mockDatasets);
  }
  if (!localStorage.getItem(STORAGE_KEYS.ENTITIES)) {
    saveToStorage(STORAGE_KEYS.ENTITIES, mockEntities);
  }
  if (!localStorage.getItem(STORAGE_KEYS.FEATURE_VIEWS)) {
    saveToStorage(STORAGE_KEYS.FEATURE_VIEWS, mockFeatureViews);
  }
  if (!localStorage.getItem(STORAGE_KEYS.JOBS)) {
    saveToStorage(STORAGE_KEYS.JOBS, mockJobs);
  }
  if (!localStorage.getItem(STORAGE_KEYS.MODELS)) {
    saveToStorage(STORAGE_KEYS.MODELS, mockModels);
  }
  if (!localStorage.getItem(STORAGE_KEYS.FEATURE_TASKS)) {
    saveToStorage(STORAGE_KEYS.FEATURE_TASKS, []);
  }
};

// 初始化存储
initializeStorage();

// Mock服务
export const mockService = {
  // 数据集相关
  datasets: {
    getAll: async (): Promise<ApiResponse<Dataset[]>> => {
      await new Promise(resolve => setTimeout(resolve, 300)); // 模拟网络延迟
      // 合并预定义的数据集和存储的数据集
      const storedDatasets = getFromStorage<Dataset>(STORAGE_KEYS.DATASETS);
      return {
        success: true,
        data: [...mockDatasets, ...storedDatasets]
      };
    },
    upload: async (file: File, name: string, description: string): Promise<ApiResponse<Dataset>> => {
      await new Promise(resolve => setTimeout(resolve, 1000)); // 模拟上传延迟
      
      // 读取文件内容
      const content = await file.text();
      const { columns, rows } = parseCSV(content);
      
      const newDataset: Dataset = {
        id: generateId(),
        name,
        description,
        uploadedAt: new Date().toISOString(),
        fileSize: file.size,
        columns,
        rows,
        type: 'raw' // 标记为原始数据集
      };
      
      const datasets = getFromStorage<Dataset>(STORAGE_KEYS.DATASETS);
      datasets.push(newDataset);
      saveToStorage(STORAGE_KEYS.DATASETS, datasets);
      
      return {
        success: true,
        data: newDataset
      };
    },
    getById: async (id: string): Promise<ApiResponse<Dataset>> => {
      await new Promise(resolve => setTimeout(resolve, 200));
      const datasets = getFromStorage<Dataset>(STORAGE_KEYS.DATASETS);
      const dataset = datasets.find(d => d.id === id);
      
      if (dataset) {
        return { success: true, data: dataset };
      } else {
        return { success: false, error: '数据集不存在' };
      }
    },
    delete: async (id: string): Promise<ApiResponse<void>> => {
      await new Promise(resolve => setTimeout(resolve, 300));
      const datasets = getFromStorage<Dataset>(STORAGE_KEYS.DATASETS);
      const filtered = datasets.filter(d => d.id !== id);
      
      if (filtered.length === datasets.length) {
        return { success: false, error: '数据集不存在' };
      }
      
      saveToStorage(STORAGE_KEYS.DATASETS, filtered);
      
      return {
        success: true
      };
    }
  },
  
  // 实体相关
  entities: {
    getAll: async (): Promise<ApiResponse<Entity[]>> => {
      await new Promise(resolve => setTimeout(resolve, 200));
      return {
        success: true,
        data: getFromStorage<Entity>(STORAGE_KEYS.ENTITIES)
      };
    },
    create: async (entity: Omit<Entity, 'id'>): Promise<ApiResponse<Entity>> => {
      await new Promise(resolve => setTimeout(resolve, 300));
      const newEntity: Entity = {
        ...entity,
        id: generateId()
      };
      
      const entities = getFromStorage<Entity>(STORAGE_KEYS.ENTITIES);
      entities.push(newEntity);
      saveToStorage(STORAGE_KEYS.ENTITIES, entities);
      
      return {
        success: true,
        data: newEntity
      };
    }
  },
  
  // 特征视图相关
  featureViews: {
    getAll: async (): Promise<ApiResponse<FeatureView[]>> => {
      await new Promise(resolve => setTimeout(resolve, 200));
      return {
        success: true,
        data: getFromStorage<FeatureView>(STORAGE_KEYS.FEATURE_VIEWS)
      };
    },
    create: async (featureView: Omit<FeatureView, 'id' | 'createdAt'>): Promise<ApiResponse<FeatureView>> => {
      await new Promise(resolve => setTimeout(resolve, 300));
      const newFeatureView: FeatureView = {
        ...featureView,
        id: generateId(),
        createdAt: new Date().toISOString()
      };
      
      const featureViews = getFromStorage<FeatureView>(STORAGE_KEYS.FEATURE_VIEWS);
      featureViews.push(newFeatureView);
      saveToStorage(STORAGE_KEYS.FEATURE_VIEWS, featureViews);
      
      return {
        success: true,
        data: newFeatureView
      };
    },
    update: async (id: string, featureView: Partial<Omit<FeatureView, 'id' | 'createdAt'>>): Promise<ApiResponse<FeatureView>> => {
      await new Promise(resolve => setTimeout(resolve, 300));
      const featureViews = getFromStorage<FeatureView>(STORAGE_KEYS.FEATURE_VIEWS);
      const index = featureViews.findIndex(fv => fv.id === id);
      
      if (index === -1) {
        return { success: false, error: '特征视图不存在' };
      }
      
      featureViews[index] = { ...featureViews[index], ...featureView };
      saveToStorage(STORAGE_KEYS.FEATURE_VIEWS, featureViews);
      
      return {
        success: true,
        data: featureViews[index]
      };
    },
    delete: async (id: string): Promise<ApiResponse<void>> => {
      await new Promise(resolve => setTimeout(resolve, 300));
      const featureViews = getFromStorage<FeatureView>(STORAGE_KEYS.FEATURE_VIEWS);
      const filtered = featureViews.filter(fv => fv.id !== id);
      
      if (filtered.length === featureViews.length) {
        return { success: false, error: '特征视图不存在' };
      }
      
      saveToStorage(STORAGE_KEYS.FEATURE_VIEWS, filtered);
      
      return {
        success: true
      };
    }
  },
  
  // 特征任务相关
  featureTasks: {
    getAll: async (): Promise<ApiResponse<FeatureTask[]>> => {
      await new Promise(resolve => setTimeout(resolve, 200));
      // 合并存储的任务和示例任务
      const storedTasks = getFromStorage<FeatureTask>(STORAGE_KEYS.FEATURE_TASKS);
      return {
        success: true,
        data: [...mockFeatureTasks, ...storedTasks]
      };
    },
    getById: async (id: string): Promise<ApiResponse<FeatureTask>> => {
      await new Promise(resolve => setTimeout(resolve, 200));
      const tasks = getFromStorage<FeatureTask>(STORAGE_KEYS.FEATURE_TASKS);
      const task = tasks.find(t => t.id === id);
      
      if (task) {
        return { success: true, data: task };
      } else {
        return { success: false, error: '任务不存在' };
      }
    },
    create: async (task: Omit<FeatureTask, 'id' | 'status' | 'progress' | 'createdAt' | 'logs'>): Promise<ApiResponse<FeatureTask>> => {
      await new Promise(resolve => setTimeout(resolve, 300));
      const newTask: FeatureTask = {
        ...task,
        id: generateId(),
        status: 'pending',
        progress: 0,
        createdAt: new Date().toISOString(),
        logs: []
      };
      
      const tasks = getFromStorage<FeatureTask>(STORAGE_KEYS.FEATURE_TASKS);
      tasks.push(newTask);
      saveToStorage(STORAGE_KEYS.FEATURE_TASKS, tasks);
      
      return {
        success: true,
        data: newTask
      };
    },
    update: async (id: string, task: Partial<Omit<FeatureTask, 'id'>>): Promise<ApiResponse<FeatureTask>> => {
      await new Promise(resolve => setTimeout(resolve, 300));
      const tasks = getFromStorage<FeatureTask>(STORAGE_KEYS.FEATURE_TASKS);
      const index = tasks.findIndex(t => t.id === id);
      
      if (index === -1) {
        return { success: false, error: '任务不存在' };
      }
      
      tasks[index] = { ...tasks[index], ...task };
      saveToStorage(STORAGE_KEYS.FEATURE_TASKS, tasks);
      
      return {
        success: true,
        data: tasks[index]
      };
    },
    delete: async (id: string): Promise<ApiResponse<void>> => {
      await new Promise(resolve => setTimeout(resolve, 300));
      const tasks = getFromStorage<FeatureTask>(STORAGE_KEYS.FEATURE_TASKS);
      const filtered = tasks.filter(t => t.id !== id);
      
      if (filtered.length === tasks.length) {
        return { success: false, error: '任务不存在' };
      }
      
      saveToStorage(STORAGE_KEYS.FEATURE_TASKS, filtered);
      
      return {
        success: true
      };
    },
    run: async (id: string): Promise<ApiResponse<void>> => {
      await new Promise(resolve => setTimeout(resolve, 300));
      const tasks = getFromStorage<FeatureTask>(STORAGE_KEYS.FEATURE_TASKS);
      const task = tasks.find(t => t.id === id);
      
      if (!task) {
        return { success: false, error: '任务不存在' };
      }
      
      // 更新任务状态为运行中
      const taskIndex = tasks.findIndex(t => t.id === id);
      tasks[taskIndex].status = 'running';
      tasks[taskIndex].progress = 0;
      tasks[taskIndex].logs = ['开始执行特征工程任务...'];
      saveToStorage(STORAGE_KEYS.FEATURE_TASKS, tasks);
      
      // 模拟任务执行过程
      let progress = 0;
      const interval = setInterval(() => {
        progress += 10;
        const updatedTasks = getFromStorage<FeatureTask>(STORAGE_KEYS.FEATURE_TASKS);
        const updatedTaskIndex = updatedTasks.findIndex(t => t.id === id);
        
        if (updatedTaskIndex === -1) {
          clearInterval(interval);
          return;
        }
        
        updatedTasks[updatedTaskIndex].progress = progress;
        updatedTasks[updatedTaskIndex].logs = [
          ...(updatedTasks[updatedTaskIndex].logs || []),
          `处理进度: ${progress}%`,
          `正在执行节点: ${Math.floor(progress / 20) + 1}`
        ];
        
        if (progress >= 100) {
          updatedTasks[updatedTaskIndex].status = 'completed';
          updatedTasks[updatedTaskIndex].completedAt = new Date().toISOString();
          updatedTasks[updatedTaskIndex].logs = [
            ...(updatedTasks[updatedTaskIndex].logs || []),
            '任务执行完成！'
          ];
          clearInterval(interval);
        }
        
        saveToStorage(STORAGE_KEYS.FEATURE_TASKS, updatedTasks);
      }, 500);
      
      return {
        success: true
      };
    },
    pause: async (id: string): Promise<ApiResponse<void>> => {
      await new Promise(resolve => setTimeout(resolve, 300));
      const tasks = getFromStorage<FeatureTask>(STORAGE_KEYS.FEATURE_TASKS);
      const task = tasks.find(t => t.id === id);
      
      if (!task) {
        return { success: false, error: '任务不存在' };
      }
      
      if (task.status !== 'running') {
        return { success: false, error: '任务未在运行中' };
      }
      
      // 更新任务状态为暂停
      const taskIndex = tasks.findIndex(t => t.id === id);
      tasks[taskIndex].status = 'pending';
      tasks[taskIndex].logs = [
        ...(tasks[taskIndex].logs || []),
        `[${new Date().toLocaleTimeString()}] 任务已暂停`
      ];
      saveToStorage(STORAGE_KEYS.FEATURE_TASKS, tasks);
      
      return {
        success: true
      };
    }
  },
  
  // 作业相关
  jobs: {
    getAll: async (): Promise<ApiResponse<Job[]>> => {
      await new Promise(resolve => setTimeout(resolve, 200));
      return {
        success: true,
        data: getFromStorage<Job>(STORAGE_KEYS.JOBS)
      };
    },
    create: async (job: Omit<Job, 'id' | 'status' | 'createdAt' | 'updatedAt'>): Promise<ApiResponse<Job>> => {
      await new Promise(resolve => setTimeout(resolve, 300));
      const newJob: Job = {
        ...job,
        id: generateId(),
        status: 'pending',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      };
      
      const jobs = getFromStorage<Job>(STORAGE_KEYS.JOBS);
      jobs.push(newJob);
      saveToStorage(STORAGE_KEYS.JOBS, jobs);
      
      // 模拟作业状态变更
      setTimeout(() => {
        const updatedJobs = getFromStorage<Job>(STORAGE_KEYS.JOBS);
        const jobIndex = updatedJobs.findIndex(j => j.id === newJob.id);
        if (jobIndex !== -1) {
          updatedJobs[jobIndex].status = 'running';
          updatedJobs[jobIndex].updatedAt = new Date().toISOString();
          saveToStorage(STORAGE_KEYS.JOBS, updatedJobs);
          
          // 模拟作业完成
          setTimeout(() => {
            const finalJobs = getFromStorage<Job>(STORAGE_KEYS.JOBS);
            const finalJobIndex = finalJobs.findIndex(j => j.id === newJob.id);
            if (finalJobIndex !== -1) {
              finalJobs[finalJobIndex].status = 'completed';
              finalJobs[finalJobIndex].updatedAt = new Date().toISOString();
              finalJobs[finalJobIndex].metrics = {
                accuracy: 0.8 + Math.random() * 0.15,
                precision: 0.75 + Math.random() * 0.15,
                recall: 0.78 + Math.random() * 0.15,
                f1Score: 0.76 + Math.random() * 0.15
              };
              saveToStorage(STORAGE_KEYS.JOBS, finalJobs);
            }
          }, 5000);
        }
      }, 2000);
      
      return {
        success: true,
        data: newJob
      };
    },
    update: async (id: string, job: Partial<Omit<Job, 'id'>>): Promise<ApiResponse<Job>> => {
      await new Promise(resolve => setTimeout(resolve, 300));
      const jobs = getFromStorage<Job>(STORAGE_KEYS.JOBS);
      const index = jobs.findIndex(t => t.id === id);
      
      if (index === -1) {
        return { success: false, error: '任务不存在' };
      }
      
      jobs[index] = { ...jobs[index], ...job };
      saveToStorage(STORAGE_KEYS.JOBS, jobs);
      
      return {
        success: true,
        data: jobs[index]
      };
    },
    run: async (id: string): Promise<ApiResponse<void>> => {
      await new Promise(resolve => setTimeout(resolve, 300));
      const jobs = getFromStorage<Job>(STORAGE_KEYS.JOBS);
      const job = jobs.find(t => t.id === id);
      
      if (!job) {
        return { success: false, error: '任务不存在' };
      }
      
      // 更新任务状态为运行中
      const jobIndex = jobs.findIndex(t => t.id === id);
      jobs[jobIndex].status = 'running';
      jobs[jobIndex].logs = ['开始执行模型训练任务...'];
      saveToStorage(STORAGE_KEYS.JOBS, jobs);
      
      // 模拟任务执行过程
      const interval = setInterval(() => {
        const updatedJobs = getFromStorage<Job>(STORAGE_KEYS.JOBS);
        const updatedJobIndex = updatedJobs.findIndex(t => t.id === id);
        
        if (updatedJobIndex === -1) {
          clearInterval(interval);
          return;
        }
        
        // 模拟日志输出
        const logMessages = [
          '加载训练数据集',
          '数据预处理完成',
          '初始化模型参数',
          '开始第1轮训练',
          '第1轮训练完成，准确率: 0.75',
          '开始第2轮训练',
          '第2轮训练完成，准确率: 0.78',
          '开始第3轮训练',
          '第3轮训练完成，准确率: 0.82',
          '开始第4轮训练',
          '第4轮训练完成，准确率: 0.85',
          '开始第5轮训练',
          '第5轮训练完成，准确率: 0.87',
          '模型训练完成！'
        ];
        
        // 随机添加一些日志
        const randomLog = logMessages[Math.floor(Math.random() * logMessages.length)];
        updatedJobs[updatedJobIndex].logs = [
          ...(updatedJobs[updatedJobIndex].logs || []),
          `[${new Date().toLocaleTimeString()}] ${randomLog}`
        ];
        
        // 随机更新进度和指标
        if (Math.random() > 0.7) {
          updatedJobs[updatedJobIndex].metrics = {
            accuracy: 0.75 + Math.random() * 0.15,
            precision: 0.75 + Math.random() * 0.15,
            recall: 0.75 + Math.random() * 0.15,
            f1Score: 0.75 + Math.random() * 0.15
          };
        }
        
        // 模拟任务完成
        if (Math.random() > 0.9) {
          updatedJobs[updatedJobIndex].status = 'completed';
          updatedJobs[updatedJobIndex].logs = [
            ...(updatedJobs[updatedJobIndex].logs || []),
            `[${new Date().toLocaleTimeString()}] 任务执行完成！`
          ];
          clearInterval(interval);
        }
        
        saveToStorage(STORAGE_KEYS.JOBS, updatedJobs);
      }, 1000);
      
      return {
        success: true
      };
    },
    stop: async (id: string): Promise<ApiResponse<void>> => {
      await new Promise(resolve => setTimeout(resolve, 300));
      const jobs = getFromStorage<Job>(STORAGE_KEYS.JOBS);
      const job = jobs.find(t => t.id === id);
      
      if (!job) {
        return { success: false, error: '任务不存在' };
      }
      
      if (job.status !== 'running') {
        return { success: false, error: '任务未在运行中' };
      }
      
      // 更新任务状态为停止
      const jobIndex = jobs.findIndex(t => t.id === id);
      jobs[jobIndex].status = 'stopped';
      jobs[jobIndex].logs = [
        ...(jobs[jobIndex].logs || []),
        `[${new Date().toLocaleTimeString()}] 任务已停止`
      ];
      saveToStorage(STORAGE_KEYS.JOBS, jobs);
      
      return {
        success: true
      };
    }
  },
  
  // 模型相关
  models: {
    getAll: async (): Promise<ApiResponse<Model[]>> => {
      await new Promise(resolve => setTimeout(resolve, 200));
      return {
        success: true,
        data: getFromStorage<Model>(STORAGE_KEYS.MODELS)
      };
    },
    save: async (modelData: Omit<Model, 'id' | 'createdAt'>): Promise<ApiResponse<Model>> => {
      await new Promise(resolve => setTimeout(resolve, 300));
      const existingModels = getFromStorage<Model>(STORAGE_KEYS.MODELS);
      
      // 如果没有提供版本号，则自动生成
      const version = modelData.version || existingModels.filter(m => m.name.startsWith(modelData.name)).length + 1;
      
      const newModel: Model = {
        ...modelData,
        id: generateId(),
        createdAt: new Date().toISOString(),
        version
      };
      
      existingModels.push(newModel);
      saveToStorage(STORAGE_KEYS.MODELS, existingModels);
      
      return {
        success: true,
        data: newModel
      };
    }
  }
};

export default mockService;